#!/bin/bash
tmp_root_dir=$PWD
echo "=================================================="
echo -e "      \e[41mOne Key Deploy MicroPython Development\e[0m"
echo "=================================================="
echo ""
echo -e "\e[32mUpdate system...\e[0m"
sudo apt-get update
sudo apt-get install -y git

echo ""
echo -e "\e[32mClone MicroPython project from github...\e[0m"
git clone --recursive https://gitee.com/mirrors/micropython.git

# read support idf hash
while read line
do
    tmp_line=`echo ${line} | sed s/[[:space:]]//g`

    if [[ $tmp_line =~ 'ESPIDF_SUPHASH_V3:=' ]] ; then
        sup_idf_hash=${tmp_line#*ESPIDF_SUPHASH_V3:=}
        break
    fi
done  < micropython/ports/esp32/Makefile

echo "-- sup_idf_hash: $sup_idf_hash";
echo ""
echo -e "\e[32mClone IDF project from github...\e[0m"
git clone https://gitee.com/EspressifSystems/esp-idf.git
cd esp-idf
git checkout $sup_idf_hash
git submodule update --init --recursive

cd $tmp_root_dir
echo ""
echo -e "\e[32mInstalling development...\e[0m"
sudo apt-get install -y gcc git wget make libncurses-dev flex bison gperf python python-pip python-setuptools python-serial python-cryptography python-future python-pyparsing python-pyelftools tar python3 python3-pip
sudo apt-get install -y python3-setuptools libssl-dev

echo ""
echo -e "\e[32mDownloading ESP32 Toolchains from Espressif...\e[0m"
if [ $(getconf WORD_BIT) = '32' ] && [ $(getconf LONG_BIT) = '64' ] ; then
    if [ -f xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz ] ; then
        if [ ! -d xtensa-esp32-elf ] ; then
            tar xvf xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz > /dev/null
        fi
    else
        wget https://dl.espressif.com/dl/xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz && tar xvf xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz > /dev/null
    fi
elif [ $(getconf LONG_BIT) = '32' ] ; then
    if [ -f xtensa-esp32-elf-linux32-1.22.0-80-g6c4433a-5.2.0.tar.gz ] ; then
        if [ ! -d xtensa-esp32-elf ] ; then
            tar xvf xtensa-esp32-elf-linux32-1.22.0-80-g6c4433a-5.2.0.tar.gz > /dev/null
        fi
    else
        wget https://dl.espressif.com/dl/xtensa-esp32-elf-linux32-1.22.0-80-g6c4433a-5.2.0.tar.gz && tar xvf xtensa-esp32-elf-linux32-1.22.0-80-g6c4433a-5.2.0.tar.gz > /dev/null
    fi
else
    echo -e "\e[31mError: not support this machine\e[0m"
    exit 0
fi

echo ""
echo -e "\e[32mInstalling Toolchains...\e[0m"
if [ -d xtensa-esp32-elf ] ; then
    echo "export PATH=\"$tmp_root_dir/xtensa-esp32-elf/bin:\$PATH\"" >> ~/.profile
    echo "export IDF_PATH=$tmp_root_dir/esp-idf" >> ~/.profile
    echo "export ESPIDF=$tmp_root_dir/esp-idf" >> ~/.profile
    source ~/.profile
    pip3 install --user -r $IDF_PATH/requirements.txt
else
    echo -e "\e[31mError: install toolchains failed\e[0m"
    exit 0
fi

echo ""
echo -e "\e[32mCompiling firmware...\e[0m"
cd $tmp_root_dir
cd micropython/mpy-cross && make && cd $tmp_root_dir
cd micropython/ports/esp32 && make
